package com.shqcjd.preinstallmobile.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.shqcjd.preinstallmobile.R;
import com.shqcjd.preinstallmobile.api.ApiService;
import com.shqcjd.preinstallmobile.app.MyApp;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallmobile.model.ResponseData;
import com.shqcjd.preinstallmobile.model.pojo.IntentEquipmentBean;
import com.shqcjd.preinstallmobile.model.pojo.PointInfoBean;
import com.shqcjd.preinstallmobile.model.pojo.RouteInfoBean;
import com.shqcjd.preinstallmobile.model.pojo.RouteInfoListBean;
import com.shqcjd.preinstallmobile.model.pojo.TaskCodeBean;
import com.shqcjd.preinstallmobile.ui.adapter.RouteAdapter;
import com.shqcjd.preinstallmobile.ui.base.BaseActivity;
import com.shqcjd.preinstallmobile.ui.base.BasePresenter;
import com.shqcjd.preinstallmobile.util.Config;
import com.shqcjd.preinstallmobile.util.ToastUtils;
import com.shqcjd.preinstallmobile.util.UIUtils;
import com.shqcjd.preinstallmobile.util.WrapContentLinearLayoutManager;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class RouteInfoActivity extends BaseActivity {

    @BindView(R.id.tv_include_title)
    TextView tvIncludeTitle;
    @BindView(R.id.tv_include_finish)
    Button tvIncludeFinish;
    @BindView(R.id.rv_route)
    RecyclerView rvRoute;
    @BindView(R.id.mv_route)
    MapView mvRoute;
    @BindView(R.id.sr_route_info)
    SwipeRefreshLayout srRouteInfo;
    @BindView(R.id.tv_route_info_content)
    TextView tvRouteInfoContent;
    @BindView(R.id.btn_route_info_inspect)
    Button btnRouteInfoInspect;
    @BindView(R.id.btn_route_info_code)
    Button btnRouteInfoCode;
    @BindView(R.id.mv_route_bottom)
    LinearLayout mvRouteBottom;
    @BindView(R.id.tv_route_name)
    TextView tv_route_name;

    private static final int REQUEST_CODE = 100;
    private Context context;
    private RouteAdapter routeAdapter;
    private List<RouteInfoListBean.ItemsBean> mList = new ArrayList<>();
    private int rId;
    private int page = 1;
    private int isRefreshOrLoadMore = 0;//0代表刷新  1代表加载更多
    private int tId = -1;
    private String taskCode;
    private int total;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_route_info;
    }

    @Override
    public void init() {
        super.init();
        rId = getIntent().getIntExtra("rId", 1);
//        rId = 22;
    }

    @Override
    public void initView() {
        super.initView();
        context = this;

        tvIncludeFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        context = this;
        srRouteInfo.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });

        btnRouteInfoInspect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RxPermissions permissions = new RxPermissions(RouteInfoActivity.this);
                permissions.setLogging(true);
                permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    startActivityForResult(new Intent(RouteInfoActivity.this, QRcodeActivity.class), REQUEST_CODE);
                                } else {
                                    ToastUtils.show(RouteInfoActivity.this, "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                }
                            }
                        });
            }
        });

        btnRouteInfoCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(context, GenerateQRcodeActivity.class);
                it.putExtra("QRcode", taskCode);
                startActivity(it);
            }
        });

        getData();
        refreshData();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initMap(savedInstanceState);
    }

    private void initMap(Bundle savedInstanceState) {
        mvRoute.onCreate(savedInstanceState);
    }

    private void initMapView(List<RouteInfoBean.PatrolPointBean> patrol_point) {
        MyApp.startLocation();
        MyApp.setOnLocationCallBack(new MyApp.OnLocationInterface() {
            @Override
            public void onLocationInterface(AMapLocation aMapLocation) {
                LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());//构造一个位置
                mvRoute.getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
            }
        });

        List<LatLng> latLngs = new ArrayList<LatLng>();
        if(patrol_point.size()==0){
            return;
        }
        for (int i = 0; i <= patrol_point.size(); i++) {
            if (i == patrol_point.size()) {
                latLngs.add(UIUtils.getGpsChangeLocation(Double.parseDouble(patrol_point.get(0).latitude), Double.parseDouble(patrol_point.get(0).longitude), context));
            } else {
                latLngs.add(UIUtils.getGpsChangeLocation(Double.parseDouble(patrol_point.get(i).latitude), Double.parseDouble(patrol_point.get(i).longitude), context));
                LatLng latLng2 = UIUtils.getGpsChangeLocation(Double.parseDouble(patrol_point.get(i).latitude), Double.parseDouble(patrol_point.get(i).longitude), context);
                Marker marker = mvRoute.getMap().addMarker(new MarkerOptions().position(latLng2).title("运维眼").snippet(""));
                marker.setObject(patrol_point.get(i).id);
            }
        }
        mvRoute.getMap().addPolyline(new PolylineOptions().
                addAll(latLngs).width(10).color(Color.argb(255, 239, 49, 49)));
        //画点
        mvRoute.getMap().setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.isInfoWindowShown()) {
                    marker.hideInfoWindow();
                } else {
                    getPointInfo(marker);
                }
                return true;
            }
        });
    }

    private void getData() {
        ApiService.routeInfoHttp(rId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<RouteInfoBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<RouteInfoBean> responseData) {
                        if (responseData.retCode != 10000) {
                            return;
                        }

                        if (!responseData.data.working) {
                            ViewGroup.LayoutParams lp = mvRouteBottom.getLayoutParams();
                            lp.width = 1;
                            lp.height = 1;
                            mvRouteBottom.setLayoutParams(lp);
                        }
                        String str = "共计:<font color='#275bc0'>" + responseData.data.total.point + "</font>个巡检点、<font color='#275bc0'>" +
                                responseData.data.total.equipment + "</font>个巡检设备、<font color='#275bc0'>" + responseData.data.total.equipment_part_item+ "</font>巡检项";
                        tvRouteInfoContent.setTextSize(12);
                        tvRouteInfoContent.setText(Html.fromHtml(str));
                        tv_route_name.setText(responseData.data.name);
                        if (responseData.data.patrol_point.size()<=0) {
                            return;
                        }
                        initMapView(responseData.data.patrol_point);

                        tId = responseData.data.task_id;
                        //生成二维码信息
                        TaskCodeBean taskCodeBean = new TaskCodeBean();
                        taskCodeBean.task_id = responseData.data.task_id;
                        taskCodeBean.user_id = responseData.data.user_id;
                        taskCodeBean.token = responseData.data.token;
                        taskCode = new Gson().toJson(taskCodeBean);

                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void refreshData() {
        refreshOrLoadMore();
        srRouteInfo.setRefreshing(true);
        isRefreshOrLoadMore = 0;
        page = 1;
        mList.clear();
        getDataList(page);
    }

    private void loadMoreData() {
        isRefreshOrLoadMore = 1;
        getDataList(page + 1);
    }

    private void refreshOrLoadMore() {
        if (routeAdapter != null) {
            routeAdapter.notifyLoadMoreToLoading();
        }
    }

    private void getDataList(int p) {
        ApiService.routeInfoListHttp(p, Config.PAGE_TOTAL, rId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<RouteInfoListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<RouteInfoListBean> responseData) {
                        if (responseData.retCode != 10000) {
                            return;
                        }
                        total = responseData.data.total;
                        mList.addAll(responseData.data.items);
                        if (routeAdapter == null) {
                            rvRoute.setLayoutManager(new WrapContentLinearLayoutManager(context));
                            routeAdapter = new RouteAdapter(mList);
                            rvRoute.setAdapter(routeAdapter);
                            routeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                    Intent it = new Intent(context, InspectionStandardActivity.class);
                                    it.putExtra("eId", mList.get(position).equipment_id);
                                    startActivity(it);
                                }
                            });
                            routeAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                                @Override
                                public void onLoadMoreRequested() {
                                    rvRoute.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            int pageSize = total % Config.PAGE_TOTAL == 0 ? total / Config.PAGE_TOTAL : total / Config.PAGE_TOTAL + 1;
                                            if (page >= pageSize) {
                                                routeAdapter.loadMoreEnd();
                                            } else {
                                                loadMoreData();
                                            }
                                        }
                                    });
                                }
                            });
                        }
                        if (isRefreshOrLoadMore == 1) {
                            page = page + 1;
                            routeAdapter.loadMoreComplete();
                        }
                        routeAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
//                        hideWaitingDialog();
                        srRouteInfo.setRefreshing(false);
                    }
                });
    }

    private void isInspectionData(String kksStr) {
        ApiService.intentEquipmentHttp(kksStr.replace("#", "%23"), tId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<IntentEquipmentBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在获取巡检信息");
                    }

                    @Override
                    public void _onNext(ResponseData<IntentEquipmentBean> responseData) {
                        if (responseData.retCode == 10000) {
                            if (responseData.data.check_gps) {
                                RxPermissions permissions = new RxPermissions(RouteInfoActivity.this);
                                permissions.setLogging(true);
                                permissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                                        .subscribe(new Consumer<Boolean>() {
                                            @Override
                                            public void accept(Boolean aBoolean) throws Exception {
                                                if (aBoolean) {
                                                    MyApp.startLocation();
                                                    MyApp.setOnLocationCallBack(new MyApp.OnLocationInterface() {
                                                        @Override
                                                        public void onLocationInterface(AMapLocation aMapLocation) {
                                                            hideWaitingDialog();
                                                            LatLng desLatLng = UIUtils.getGpsChangeLocation(responseData.data.latitude, responseData.data.longitude, context);
                                                            //当前坐标
                                                            double cLongitude = aMapLocation.getLongitude();
                                                            double cLatitude = aMapLocation.getLatitude();
                                                            float distance = AMapUtils.calculateLineDistance(desLatLng, new LatLng(cLatitude, cLongitude));
                                                            if (distance < Config.INSPECTION_DISTANCE) {
                                                                if (responseData.data.isgroup) {
                                                                    Intent it = new Intent(context, EquipmentGroupActivity.class);
                                                                    it.putExtra("kks", kksStr);
                                                                    it.putExtra("tId", tId);
                                                                    startActivity(it);
                                                                } else {
                                                                    Intent it = new Intent(context, EquipmentInspectionActivity.class);
                                                                    it.putExtra("tId", tId);
                                                                    it.putExtra("kks", kksStr);
                                                                    startActivity(it);
                                                                }
                                                            } else {
                                                                Toast.makeText(context, "当前位置距离巡检点超过了1000米，请靠近一点再试试", Toast.LENGTH_SHORT).show();
                                                            }
                                                        }
                                                    });
                                                } else {
                                                    ToastUtils.show(RouteInfoActivity.this, "巡检需要获取定位的权限", Toast.LENGTH_SHORT);
                                                }
                                            }
                                        });

                            } else {
                                if (responseData.data.isgroup) {
                                    Intent it = new Intent(context, EquipmentGroupActivity.class);
                                    it.putExtra("kks", kksStr);
                                    it.putExtra("tId", tId);
                                    startActivity(it);
                                } else {
                                    Intent it = new Intent(context, EquipmentInspectionActivity.class);
                                    it.putExtra("tId", tId);
                                    it.putExtra("kks", kksStr);
                                    startActivity(it);
                                }
                            }
                        } else {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                        Toast.makeText(context, "任务不存在", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void getPointInfo(Marker marker) {
        ApiService.routePointInfoHttp((Integer) marker.getObject(), rId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<PointInfoBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<List<PointInfoBean>> responseData) {
                        if (responseData.retCode == 10000) {
                            String str = "";
                            for (int i = 0; i < responseData.data.size(); i++) {
                                str = str + responseData.data.get(i).name + "\n"
                                        + responseData.data.get(i).manufacturer + "\n"
                                        + responseData.data.get(i).kks + "\n";
                            }
                            marker.setSnippet(str);
                            marker.showInfoWindow();
                        } else {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_CODE == requestCode && RESULT_OK == resultCode) {
            String value = data.getStringExtra("qr_code_key");
            qCode(value);
        }
    }

    private void qCode(String kksStr) {
        if (tId != -1) {
            isInspectionData(kksStr);
        } else {
            Toast.makeText(context, "当前网络异常", Toast.LENGTH_SHORT).show();
        }
    }

    private static final double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 依据两点间经纬度坐标（double值），计算两点间距离，
     *
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return 距离：单位为公里
     */
    public static double DistanceOfTwoPoints(double lat1, double lng1,
                                             double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        Log.i("距离", s + "");
        return s;
    }


    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mvRoute.onResume ()，重新绘制加载地图
        mvRoute.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mvRoute.onPause ()，暂停地图的绘制
        mvRoute.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mvRoute.onDestroy()，销毁地图
        mvRoute.onDestroy();
    }

}
